﻿using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Data.Entity;
using System.Web.Mvc;
using TS2015.Models;

using System.Web;
using System;
using System.Data.Entity.Validation;
using System.Text;
using System.Collections.Generic;
using System.Collections;

namespace TS2015.Controllers
{
    public class CommonController : Controller
    {
        TS2015Context db = new TS2015Context();
        // GET: Common
        List<SelectListItem> mess = new List<SelectListItem>();

        [OutputCache(Duration = 5)]
        [ChildActionOnly]
        public PartialViewResult Banner()
        {
            return PartialView();
        }     

        [OutputCache(Duration = 5)]
        [ChildActionOnly]
        public PartialViewResult Menu()
        {
            return PartialView();
        }

        [OutputCache(Duration = 5)]
        [ChildActionOnly]
        public PartialViewResult NavbarLeft()
        {
            ViewBag.LuongTruyCap = db.TbThongKes.First().LuongTruyCap;
            return PartialView();
        }

        [ChildActionOnly]
        [OutputCache(Duration = 5)]
        public PartialViewResult Slide()
        {
            var slides = db.TbSlides.OrderByDescending(m => m.ThuTu).ToArray();

            return PartialView(slides);
        }

         [OutputCache(Duration = 5)]
         [ChildActionOnly]
        public PartialViewResult Footer()
        {
            return PartialView();
        }

     
        public string CheckCMND(string CMND)
        {
            if (CMND.Trim() != "")
            {
                var Check = db.TbThiSinhs.Where(m => m.CMND.ToLower().Trim() == CMND.ToLower().Trim());

                if (Check.Count() > 0)
                {
                    return "True";
                }
                else
                {
                    return "False";
                }
            }
            else
            {
                return "Empty";
            }
        }
        public bool CheckMajor(string major)
        {
            if (major.Trim() != "")
            {
                var Check = db.TbChuyenNganhs.Where(m => m.MaChuyenNganh.ToLower().Trim() == major.ToLower().Trim()).First().ChatLuongCao;
                return Check;
            }
            else
            {
                return false;
            }
        }
        public string CheckEmail(string Email)
        {
            if (Email.Trim() != null)
            {
                var Check = db.TbThiSinhs.Where(m => m.Email.ToLower().Trim() == Email.ToLower().Trim());

                if (Check.Count() > 0)
                {
                    return "True";
                }
                else
                {
                    return "False";
                }
            }
            else
            {
                return "Empty";
            }
        }
        [HttpGet]
        public JsonResult GetMajorByPhylum(int manganh)
        {
            var major = from c in db.TbChuyenNganhs
                        where c.IDNganh == manganh
                        select c;
            return Json(new SelectList(major.OrderBy(m => m.TenChuyenNganh).ToList(), "MaChuyenNganh", "TenChuyenNganh"), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetPhylumByGroup(int TLID, string makhoithi)
        {
            //int Te = Int32.Parse(Request.Form["lbTrainingSystem"]);
            var LoadTrainingLevel = db.TbBacDaoTaos.Where(m => m.MaBacDT == TLID).FirstOrDefault().TenBacDT;
            var phylumD = db.TbNganhs.Where(m => m.MaNganh.ToString().Contains("D") && m.MaKhoiThi == makhoithi);
            var phylumC = db.TbNganhs.Where(m => m.MaNganh.ToString().Contains("C") && m.MaKhoiThi == makhoithi);
            if (LoadTrainingLevel.ToLower().Trim() == "đại học")
            {
                return Json(new SelectList(phylumD.ToList(), "IDNganh", "TenNganh"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new SelectList(phylumC.ToList(), "IDNganh", "TenNganh"), JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult GetPhylumByGroupVocational(string makhoithi)
        {
           
            var phylumC = db.TbNganhs.Where(m => m.MaNganh.Contains("C") && m.MaKhoiThi == makhoithi);
            return Json(new SelectList(phylumC.ToList(), "IDNganh", "TenNganh"), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetProvinceByCommune(string matinh)
        {
            var commune = from c in db.TbHuyens
                          where c.MaTinh == matinh
                          select c;
            return Json(new SelectList(commune.OrderBy(m => m.TenHuyen).ToList(), "MaHuyen", "TenHuyen"), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetHighSchoolByProvince(string matinh)
        {
            var highschool = from c in db.TbTruongTHPTs
                             where c.MaTinh == matinh
                             select c;
            return Json(new SelectList(highschool.ToList(), "IDTruong", "TenTruong"), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetGraduateSubjectBySubjectCustom(int mamon, string makhoi)
        {
            var monthi = from c in db.TbMonTotNghieps
                         where c.MaMon != mamon && c.TenMon != "Toán" && c.TenMon != "Tiếng anh" && c.TenMon != "Ngữ Văn"
                         select c;
            return Json(new SelectList(monthi.ToList(), "MaMon", "TenMon"), JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetGraduateSubjectByGroup(int mamontuychon, string makhoithi)
        {
            var monthi = from c in db.TbKhoiThi_MonTotNghieps
                         where c.TbMonTotNghiep.TenMon != "Toán" && c.TbMonTotNghiep.TenMon != "Tiếng anh" && c.TbMonTotNghiep.TenMon != "Ngữ Văn"
                               && c.TbMonTotNghiep.MaMon != mamontuychon && c.MaKhoiThi == makhoithi
                         select new
                         {
                             MaMon = c.MaMon,
                             TenMon = c.TbMonTotNghiep.TenMon
                         };

            return Json(monthi, JsonRequestBehavior.AllowGet);
        }
 
        public string GetID()
        {
            string ID = "";
            var MaTS = (from p in db.TbThiSinhs orderby (p.MaTS) descending select p).FirstOrDefault();
            int Cuoi;
            string LastID;
            int NextID;

            if (MaTS == null)
            {
                NextID = 1;
            }
            else
            {
                Cuoi = Convert.ToInt32(MaTS.MaTS.ToString().Substring(4)) + 1;
                LastID = Cuoi.ToString();
                if (LastID == null)
                {
                    LastID = DateTime.Now.ToString("yyyy") + "00001";
                }
                NextID = Cuoi;
            }
            ID = DateTime.Now.ToString("yyyy") + NextID.ToString("00000");
            return ID;
        }

        public ActionResult PhieuHoanThanh()
        {
            return View("PhieuHoanThanh");
        }

        public ActionResult Profile()
        {
            return View("Profile");
        }
         
        [ChildActionOnly]
        public ActionResult TinNoiBat([Range(0, int.MaxValue)]int? SoLuong)
        {     
            int _SoLuong = SoLuong ?? -1;

            var data = db.TbTinTucs.Where(e => e.NoiBat == true);

            if (_SoLuong > -1)
                return PartialView("_TinNoiBat", data.Take(_SoLuong));
            return PartialView("_TinNoiBat", data);
        }
         [ChildActionOnly]
        public ActionResult TinLienQuan(int MaTinTuc, int MaTheLoai)
        {
            var data1 = db.TbTinTucs.Where(e => e.MaTinTuc < MaTinTuc && e.MaTheLoai==MaTheLoai).OrderByDescending(e=>e.MaTinTuc).Take(5).ToList();
            var data2 = db.TbTinTucs.Where(e => e.MaTinTuc > MaTinTuc && e.MaTheLoai == MaTheLoai).OrderBy(e => e.MaTinTuc).Take(5).ToList();
            return PartialView("_TinLienQuan", data1.Concat(data2));
        }       

        [ChildActionOnly]
        [ValidateInput(false)]
        public ActionResult TinTheoTheLoai(int MaTheLoai, [Range(0, int.MaxValue)]int? SoLuong)
        { 
            int _SoLuong = SoLuong ?? -1;

            var data = db.TbTinTucs.Include(e => e.TbTheLoai).Where(e => e.MaTheLoai == MaTheLoai).OrderByDescending(e=>e.NgayDang);

            if (data == null)
                return HttpNotFound();

            if (_SoLuong > -1)
                return PartialView("_TinTheoTheLoai", data.Take(_SoLuong));

            return PartialView("_TinTheoTheLoai", data);
        }

        public ActionResult XacNhanDangKy()
        {
            return View();
        } 

        [HttpPost]
        public ActionResult XacNhanDangKy(string capcha, bool Agree=false)
        {
            if (Agree == false)
                return View();
            else
            {
      
                return RedirectToAction("PhieuDK");
            }
        }

        public ActionResult ChiTiet(int id, string seoName)
        {
            try
            {
                var data = db.TbTinTucs.First(e => e.MaTinTuc == id);

                if (data == null)
                    return HttpNotFound();
                //Cap nhat so luot xem
                data.LuotXem = data.LuotXem + 1;
                db.Entry(data).State = EntityState.Modified;
                db.SaveChanges();

                string strSEO = DuLieuChung.NonUnicode(data.TieuDe);
                if (seoName != strSEO)
                    return RedirectToRoute("ChiTiet", new { id = id, seoName = strSEO });

                return View(data);
            }
            catch
            {
                return HttpNotFound();
            }

        }

        public ActionResult PhieuDK(string MaTS)
        {
            //if (!(bool)ViewBag.Agree)
            //    return RedirectToAction("XacNhanDangKy" );

            var time = db.TbThoiGians.OrderByDescending(m => m.MaTG).FirstOrDefault();

            if (time!=null && (time.Mo.Date > DateTime.Now.Date || time.Dong.Date < DateTime.Now.Date))
            {
                ViewBag.Error = true;
                ViewBag.Mo = time.Mo.ToString("dd/MM/yyyy");
                ViewBag.Dong = time.Dong.ToString("dd/MM/yyyy");
                
                return View();                
            }
            
            ViewBag.LienKet = false;
            ViewBag.HeTrungCap = false;
            ViewBag.HeCaoDang = false;
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "Hà Nội", Value = "0" });
            list.Add(new SelectListItem { Text = "Trung cấp Kinh tế Kỹ thuật Hồng Lam", Value = "1" });
            ViewBag.NoiDaoTao = list.ToList();

            TbThiSinh ThiSinh = new TbThiSinh();
          
                //if (Session["TenDangNhap"] != null)
                //    MaTS = MaTS ?? Session["TenDangNhap"].ToString();

                if (ThiSinh.MaTS == null)
                {
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                    ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
                    ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
                    ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
                    //ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
                    //ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
                    //ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
                    //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
                    ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
                    //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
                    //ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
                    ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
                    ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
                    ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
                    //ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                }

            if (Request.IsAjaxRequest())
                return PartialView(ThiSinh);

            return View(ThiSinh);
        }

        [HttpPost]
        public ActionResult PhieuDK(TbThiSinh item, bool LienKet = false, bool HeTrungCap=false, bool HeCaoDang=false)
        {
            string randomPass ="";
            if (item != null)
            {
                TbNguoiDung nguoidung;
                TbDiemTotNghiep diem;
                item.NgayDangKi = DateTime.Now;
                TbThiSinh_BacDaoTao CD_TL;
                
                //item.LanSuaCuoi = DateTime.Now;
                if (item.MaTS != null)
                {
                    db.Entry(item).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else
                {
                    //if (ModelState.IsValid)
                    //{
                    item.MaTS = GetID();
                    db.TbThiSinhs.Add(item);
                    TbThiSinh_Truong Lop10 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong10"].Trim()), Lop = 10 };
                    db.TbThiSinh_Truongs.Add(Lop10);
                    TbThiSinh_Truong Lop11 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong11"].Trim()), Lop = 11 };
                    db.TbThiSinh_Truongs.Add(Lop11);
                    TbThiSinh_Truong Lop12 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong12"].Trim()), Lop = 12 };
                    db.TbThiSinh_Truongs.Add(Lop12);
                    //item.NgayDongTien = DateTime.Now;
                    //item.NgayHoanThanhDK = DateTime.Now;

                    if (Request.Form["HinhThucDK"] == "0")
                    {
                        item.MaTruongDH = "DDL";
                        TbDiemTotNghiep MonTuyChon;
                        CD_TL = new TbThiSinh_BacDaoTao { MaTS = item.MaTS, DKThem = false, MaBacDT = int.Parse(Request.Form["BacDaoTao1"].Trim()), TrungTuyen = null };
                        db.TbThiSinh_BacDaoTaos.Add(CD_TL);

                        MonTuyChon = new TbDiemTotNghiep { MaMon = int.Parse(Request.Form["MaMon"].Trim()), MaTS = item.MaTS };
                        db.TbDiemTotNghieps.Add(MonTuyChon);
                        string[] thiThem = Request.Form["checkbox"].Split(',');
                        for (int i = 0; i < thiThem.Length; i++)
                        {
                            diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = int.Parse(thiThem[i].Trim()) };
                            db.TbDiemTotNghieps.Add(diem);
                        }
                        if (Request.Form["ChatLuongCao"] != "")
                        {
                            item.ChatLuongCao = bool.Parse(Request.Form["ChatLuongCao"].Trim());
                        }
                        
                    }
                    else if (Request.Form["HinhThucDK"] == "1")
                    {
                        item.MaTruongDH = "DDL";
                        // Điểm 3 môn Toán, Văn, Anh
                        string[] MangMaMon1 = Request.Form["SubjectRecruitmentBasic"].Split(',');
                        string[] MangDiemMon1 = Request.Form["MarkRecruitmentBasic"].Split(',');
                        string ten = "";
                        for (int i = 0; i < MangMaMon1.Length; i++)
                        {
                            if (MangDiemMon1[i].Trim() != "")
                            {
                                ten = MangMaMon1[i];
                                var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                                diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon, Diem = double.Parse(MangDiemMon1[i].Trim()) };
                                db.TbDiemTotNghieps.Add(diem);
                            }
                            else
                            {
                                ten = MangMaMon1[i];
                                var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                                diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon };
                                db.TbDiemTotNghieps.Add(diem);
                            }
                            
                        }
                        //Điểm môn tùy chọn
                        if (Request.Form["ddlMarkRecruitmentBasic"].Trim() != "")
                        {
                            diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(Request.Form["ddlSubjectRecruitmentBasic"].Trim()), Diem = double.Parse(Request.Form["ddlMarkRecruitmentBasic"].Trim()) };
                            db.TbDiemTotNghieps.Add(diem);
                        }
                        CD_TL = new TbThiSinh_BacDaoTao { MaTS = item.MaTS, DKThem = false, MaBacDT = int.Parse(Request.Form["BacDaoTao3"].Trim()), TrungTuyen = null };
                        db.TbThiSinh_BacDaoTaos.Add(CD_TL);
                        //item.MaHeDaoTao = Int32.Parse(Request.Form["HDT"]);
                    }
                    else
                    {
                        // Điểm 3 môn Toán, Văn, Anh
                        string[] MangMaMon1 = Request.Form["SubjectRecruitment"].Split(',');
                        string[] MangDiemMon1 = Request.Form["MarkRecruitment"].Split(',');
                        string ten = "";
                        for (int i = 0; i < MangMaMon1.Length; i++)
                        {
                            if (MangDiemMon1[i].Trim() != "")
                            {
                                ten = MangMaMon1[i];
                                var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                                diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon, Diem = double.Parse(MangDiemMon1[i].Trim()) };
                                db.TbDiemTotNghieps.Add(diem);
                            }
                            else
                            {
                                ten = MangMaMon1[i];
                                var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                                diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon };
                                db.TbDiemTotNghieps.Add(diem);
                            }
                            
                        }
                        //Điểm môn tùy chọn
                        if (Request.Form["ddlMarkRecruitment"].Trim() != "")
                        {
                            diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(Request.Form["ddlSubjectRecruitment"].Trim()), Diem = double.Parse(Request.Form["ddlMarkRecruitment"].Trim()) };
                            db.TbDiemTotNghieps.Add(diem);
                        }
                        // Điểm môn thi thêm
                        if (Request.Form["IDInput"] != null && Request.Form["MarkSubject"] != null)
                        {
                            string[] MangMaMon3 = Request.Form["IDInput"].Split(',');
                            string[] MangDiemMon3 = Request.Form["MarkSubject"].Split(',');
                            for (int i = 0; i < MangMaMon3.Length; i++)
                            {
                                if (MangDiemMon3[i].Trim() != "")
                                {
                                    diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(MangMaMon3[i]), Diem = double.Parse(MangDiemMon3[i]) };
                                    db.TbDiemTotNghieps.Add(diem);
                                }
                                else
                                {
                                    diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(MangMaMon3[i]) };
                                    db.TbDiemTotNghieps.Add(diem);
                                }
                            }
                        }
                        CD_TL = new TbThiSinh_BacDaoTao { MaTS = item.MaTS, DKThem = false, MaBacDT = int.Parse(Request.Form["BacDaoTao2"].Trim()), TrungTuyen = null };
                        db.TbThiSinh_BacDaoTaos.Add(CD_TL);
                    }
                    // Lưu hệ khác
                    if (LienKet)
                    {
                        item.LienKetQT = true;
                    }
                    if (HeCaoDang)
                    {
                        var Ma1 = (from a in db.TbBacDaoTaos
                                  join b in db.TbHeDaoTaos on a.MaHeDaoTao equals b.MaHeDaoTao
                                  where b.TenHeDaoTao.ToLower().Trim() == "nghề" && a.TenBacDT.ToLower().Trim() == "cao đẳng"
                                  select a.MaBacDT).First();
                        db.TbThiSinh_BacDaoTaos.Add(new TbThiSinh_BacDaoTao { MaBacDT = Ma1, MaTS = item.MaTS,DKThem=true, NoiDaoTao = int.Parse(Request.Form["NoiDaoTao"].Trim()), TrungTuyen = null });
                    }
                    if (HeTrungCap)
                    {
                        var Ma2 = (from a in db.TbBacDaoTaos
                                   join b in db.TbHeDaoTaos on a.MaHeDaoTao equals b.MaHeDaoTao
                                   where b.TenHeDaoTao.ToLower().Trim() == "chính quy" && a.TenBacDT.ToLower().Trim() == "trung cấp"
                                   select a.MaBacDT).First();
                        db.TbThiSinh_BacDaoTaos.Add(new TbThiSinh_BacDaoTao { MaBacDT = Ma2, MaTS = item.MaTS,DKThem=true, NoiDaoTao = int.Parse(Request.Form["NoiDaoTao"].Trim()), TrungTuyen = null });
                    }
                    //item.MaHeDaoTao = Int32.Parse(Request.Form["HDT"]);
                    string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                    var random = new Random();
                    randomPass = new string(
                        Enumerable.Repeat(chars, 6)
                                  .Select(s => s[random.Next(s.Length)])
                                  .ToArray());
                    nguoidung = new TbNguoiDung { TenDangNhap = item.MaTS, Email = item.Email, MaQuyen = db.TbQuyens.Where(e => e.Quyen.ToLower() == "thí sinh").FirstOrDefault().MaQuyen, MatKhau = DuLieuChung.MaHoaMD5(randomPass), KhoaTaiKhoan = 0 };
                    db.TbNguoiDungs.Add(nguoidung);
                    SaveChanges(db);
                    //}                    
                }
            }
            return RedirectToAction("GuiTinNhanXacNhan", new { MaTS = item.MaTS, Pass = randomPass });
        }

        public ActionResult GuiTinNhanXacNhan(string MaTS, string Pass)
        {
            ViewBag.MaTS = MaTS;
            ViewBag.Pass = Pass;
            return View();
        }
        private void SaveChanges(DbContext context)
        {
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                StringBuilder sb = new StringBuilder();

                foreach (var failure in ex.EntityValidationErrors)
                {
                    sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
                    foreach (var error in failure.ValidationErrors)
                    {
                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                        sb.AppendLine();
                    }
                }

                throw new DbEntityValidationException(
                    "Entity Validation Failed - errors follow:\n" +
                    sb.ToString(), ex
                ); // Add the original exception as the innerException
            }
        }
        
        public JsonResult GetTLByTS(string TSID)
        {
            return Json(new SelectList(db.TbBacDaoTaos.Where(m => m.MaHeDaoTao.ToString().Trim() == TSID.Trim() && m.TenBacDT.ToLower().Trim() != "trung cấp").ToList(), "MaBacDT", "TenBacDT"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult Step2_Examination()
        {
            //TbThiSinh ThiSinh = new TbThiSinh();
            //if (ModelState.IsValid)
            //{
            //    if (Session["TenDangNhap"] != null)
            //        MaTS = MaTS ?? Session["TenDangNhap"].ToString();

            //    if (MaTS == null)
            //    {
                    List<SelectListItem> list = new List<SelectListItem>();
                    list.Add(new SelectListItem { Text = "Có", Value = "True" });
                    list.Add(new SelectListItem { Text = "Không", Value = "False" });
                    ViewBag.ChatLuongCao = list.ToList();
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.Trim() == "chính quy" || m.TenHeDaoTao.Trim() == "liên thông").ToList(), "MaHeDaoTao", "TenHeDaoTao");
                    //ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                    //ViewBag.Tinh = new SelectList(db.TbTinhs.ToLisrt(), "MaTinh", "TenTinh");
                    ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
                    //ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
                    //ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
                    //ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
                    //ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
                    //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
                    //ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
                    //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
                    //ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
                    //ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
                    //ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
                    ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
                    //ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");

            if (Request.IsAjaxRequest())
                return PartialView();

            return View();
        }
        public ActionResult Step2_Recruiting()
        {
            //TbThiSinh ThiSinh = new TbThiSinh();
            //if (ModelState.IsValid)
            //{
            //    if (Session["TenDangNhap"] != null)
            //        MaTS = MaTS ?? Session["TenDangNhap"].ToString();

            //    if (MaTS == null)
            //    {
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "Có", Value = "True" });
            list.Add(new SelectListItem { Text = "Không", Value = "False" });
            ViewBag.ChatLuongCao = list.ToList();
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.Trim() == "chính quy" || m.TenHeDaoTao.Trim() == "liên thông").ToList(), "MaHeDaoTao", "TenHeDaoTao");
            //ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
            //ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            //ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
            ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
            ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
            //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
            ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
            //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
            //ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
            //ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
            //ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
            ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
            //ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
      


            if (Request.IsAjaxRequest())
            return PartialView();

            return View();
        }
        public ActionResult Step2_RecruitingBasic()
        {
            //TbThiSinh ThiSinh = new TbThiSinh();
            //if (ModelState.IsValid)
            //{
            //    if (Session["TenDangNhap"] != null)
            //        MaTS = MaTS ?? Session["TenDangNhap"].ToString();

            //    if (MaTS == null)
            //    {
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "Có", Value = "True" });
            list.Add(new SelectListItem { Text = "Không", Value = "False" });
            ViewBag.ChatLuongCao = list.ToList();
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.Trim() == "chính quy" || m.TenHeDaoTao.Trim() == "liên thông").ToList(), "MaHeDaoTao", "TenHeDaoTao");
            //ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
            //ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            //ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
            ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
            ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
            //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
            ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
            //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
            //ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
            //ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
            //ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
            ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
            //ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");

            if (Request.IsAjaxRequest())
            return PartialView();

            return View();
        }

        #region Vocational
        public ActionResult DKNghe()
        {
            ViewBag.LienKet = false;
            ViewBag.HeTrungCap = false;
            ViewBag.HeCaoDang = false;
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "Hà Nội", Value = "0" });
            list.Add(new SelectListItem { Text = "Trung cấp Kinh tế Kỹ thuật Hồng Lam", Value = "1" });
            ViewBag.NoiDaoTao = list.ToList();

            TbThiSinh ThiSinh = new TbThiSinh();
            if (ModelState.IsValid)
            {
                ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
                ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
                ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
                ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
                ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
                ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
                ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
                ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
                ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
                ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
                ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
            }


            if (Request.IsAjaxRequest())
                return PartialView(ThiSinh);

            return View(ThiSinh);
        }
        [HttpPost]
        public ActionResult DKNghe(TbThiSinh item,bool LienKet = false, bool HeTrungCap=false, bool HeCaoDang=false)
        {
            string randomPass = "";
            bool state = false;
            if (item != null)
            {
                TbNguoiDung nguoidung;
                item.NgayDangKi = DateTime.Now;
                //item.NgaySinh = DateTime.Now;
                if (item.MaTS != null)
                {
                    db.Entry(item).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else
                {
                    //if (ModelState.IsValid)
                    //{
                    item.MaTS = GetID();
                    item.MaTruongDH = "DDL";
                    db.TbThiSinhs.Add(item);
                    TbThiSinh_Truong Lop10 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong10"].Trim()), Lop = 10 };
                    db.TbThiSinh_Truongs.Add(Lop10);
                    TbThiSinh_Truong Lop11 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong11"].Trim()), Lop = 11 };
                    db.TbThiSinh_Truongs.Add(Lop11);
                    TbThiSinh_Truong Lop12 = new TbThiSinh_Truong { MaTS = item.MaTS, IDTruong = int.Parse(Request.Form["IDTruong12"].Trim()), Lop = 12 };
                    db.TbThiSinh_Truongs.Add(Lop12);
                    if (LienKet)
                    {
                        item.LienKetQT = true;
                    }
                    if (HeCaoDang)
                    {
                        var Ma1 = (from a in db.TbBacDaoTaos
                                   join b in db.TbHeDaoTaos on a.MaHeDaoTao equals b.MaHeDaoTao
                                   where b.TenHeDaoTao.ToLower().Trim() == "nghề" && a.TenBacDT.ToLower().Trim() == "cao đẳng"
                                   select a.MaBacDT).First();
                        db.TbThiSinh_BacDaoTaos.Add(new TbThiSinh_BacDaoTao { MaBacDT = Ma1, MaTS = item.MaTS, DKThem = true, NoiDaoTao = int.Parse(Request.Form["NoiDaoTao"].Trim()), TrungTuyen = null });
                    }
                    if (HeTrungCap)
                    {
                        var Ma2 = (from a in db.TbBacDaoTaos
                                   join b in db.TbHeDaoTaos on a.MaHeDaoTao equals b.MaHeDaoTao
                                   where b.TenHeDaoTao.ToLower().Trim() == "chính quy" && a.TenBacDT.ToLower().Trim() == "trung cấp"
                                   select a.MaBacDT).First();
                        db.TbThiSinh_BacDaoTaos.Add(new TbThiSinh_BacDaoTao { MaBacDT = Ma2, MaTS = item.MaTS, DKThem = true, NoiDaoTao = int.Parse(Request.Form["NoiDaoTao"].Trim()), TrungTuyen = null });
                    }
                    string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                    var random = new Random();
                    randomPass = new string(
                        Enumerable.Repeat(chars, 6)
                                  .Select(s => s[random.Next(s.Length)])
                                  .ToArray());
                    //item.MaHeDaoTao = HDT;
                    //item.MaHeDaoTao = LoadTrainingSystem;
                    db.TbThiSinhs.Add(item);
                    nguoidung = new TbNguoiDung { TenDangNhap = item.MaTS, Email = item.Email, MaQuyen = db.TbQuyens.Where(e => e.Quyen.ToLower() == "thí sinh").FirstOrDefault().MaQuyen, MatKhau = DuLieuChung.MaHoaMD5(randomPass), KhoaTaiKhoan = 0 };
                    db.TbNguoiDungs.Add(nguoidung);
                    SaveChanges(db);
                    //}                    
                }
            }
            return RedirectToAction("GuiTinNhanXacNhan", new { MaTS = item.MaTS, Pass = randomPass });

        }
        #endregion

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

